package com.efounder.email.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.email.dao.AttachmentsDAO;
import com.efounder.email.dao.OutboxEmailsDAO;
import com.efounder.email.db.EmailsDbHelper;
import com.efounder.email.model.Email;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AndroidEnvironmentVariable;
import com.efounder.util.GetTokenDataByPO;
import com.efounder.util.GlobalMap;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.ResStringUtil;
import com.efounder.widget.PullToRefreshSwipeMenuListView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

/**
 * 发件箱Activity
 *
 * @author yqs
 */
public class EmailOutBoxAct extends Activity implements OnClickListener,
        OnItemClickListener {
    private int page = 1;// 邮箱第一页20条数据
    final static String TAG = "EmailOutBoxAct";
    private TextView titleTextView;// 发件箱标题
    private ImageView backImageView;// 返回按钮
    private ImageView inboxWrite;// 写邮件
    private SwipeMenuItem readItem;// 侧滑已读按钮
    private EditText etSearch;// 搜索
    private ImageView ivClearText;// 搜索清除按钮
    private RelativeLayout shoujianRelativeLayout;
    private FrameLayout frameLayout;
    private SwipeMenuCreator creator, creator2;
    private PullToRefreshSwipeMenuListView listView;
    private SmartRefreshLayout mSrl;
    private ArrayList<Email> listems;
    private ListAdapter adapter;
    private int deleteTag = -1;// 删除位置标记
    private Handler mHandler;

    private Map<String, EFDataSet> map;
    private EFDataSet emailEFDataSet;

    private OutboxEmailsDAO outboxEmailsDAO;
    EmailsDbHelper dbHelper;
    private String emailType = null;
    private String boxType = null;
    String userId = AndroidEnvironmentVariable.getUserID();
    // tokenid
    private String tokenId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.shoujianxiang_layout);
        etSearch = (EditText) findViewById(R.id.et_search);// 搜索文字编辑框
        ivClearText = (ImageView) findViewById(R.id.ivClearText);// 搜索框删除按钮
        frameLayout = (FrameLayout) findViewById(R.id.layoutContainer);
        listView = (PullToRefreshSwipeMenuListView) findViewById(R.id.inbox_listview);
        frameLayout.setOnClickListener(this);
        dbHelper = new EmailsDbHelper(this);
        RelativeLayout include = (RelativeLayout) findViewById(R.id.include);
        include.setBackgroundResource(R.color.red_ios);
        LinearLayout leftbacklayout = (LinearLayout) findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.VISIBLE);
        TextView title = (TextView) findViewById(R.id.fragmenttitle);
        leftbacklayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dbHelper.close();
                finish();
            }
        });
        emailType = (String) getIntent().getSerializableExtra("emailtype");
        boxType = getIntent().getStringExtra("boxtype");
        tokenId = GlobalMap.getProperty(emailType + "TokenId", "");
        if ("DPEMAIL".equals(emailType)) {
            title.setText(ResStringUtil.getString(R.string.mobile_lib_email_outbox_headquarters));
        } else if ("EMAIL".equals(emailType)) {
            title.setText(ResStringUtil.getString(R.string.mobile_lib_email_outbox_puguang));
        } else {
            title.setText(ResStringUtil.getString(R.string.mobile_lib_email_outbox));
        }
        title.setTextColor(Color.WHITE);
        Button closeButton = (Button) findViewById(R.id.closeButton);
        closeButton.setVisibility(View.VISIBLE);
        closeButton.setBackgroundResource(R.drawable.inbox_write_white);
        closeButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EmailOutBoxAct.this,
                        EmailWriteAct.class);
                intent.putExtra("emailtype", emailType);
                startActivity(intent);

            }
        });
        outboxEmailsDAO = new OutboxEmailsDAO(this);
        listems = new ArrayList<Email>();

        adapter = new ListAdapter(listems);
        listView.setAdapter(adapter);
        mSrl = (SmartRefreshLayout) findViewById(R.id.srl);
        mSrl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page = page + 1;
                loadOutBoxData(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                outboxEmailsDAO.deleteDataByType(emailType);// 清空表中最近的20条邮件
                new AttachmentsDAO(EmailOutBoxAct.this).deleteTableData(emailType, boxType);
                loadOutBoxData(page);
            }
        });
        mHandler = new Handler();
        listView.setOnItemClickListener(this);
        // 左滑动
        leftSlide();
        initListener();

        // 加载数据
        // loadDataByNet();
        // 加载总部邮箱 发件箱数据

        // 如果数据库中的数据条数为0，从服务器请求数据

        // if (outboxEmailsDAO.getEmailTypeCount(emailType, userId) < 1) {
        loadOutBoxData(page);
        // } else {
        //
        // listems = outboxEmailsDAO.queryEmails(emailType, userId);
        // adapter.updateListView(listems);
        // }

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        dbHelper.close();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.inbox_write) {
            Intent intent = new Intent(EmailOutBoxAct.this, EmailWriteAct.class);
            intent.putExtra("emailtype", emailType);
            intent.putExtra("boxtype", boxType);
            startActivity(intent);
        } else if (id == R.id.layoutContainer) {

        }
//		switch (id) {
//		// 写邮件
//		case R.id.inbox_write:
//
//			Intent intent = new Intent(EmailOutBoxAct.this, EmailWriteAct.class);
//			intent.putExtra("emailtype", emailType);
//			intent.putExtra("boxtype", boxType);
//			startActivity(intent);
//
//			break;
//		// 搜索框layout
//		case R.id.layoutContainer:
//			// shoujianRelativeLayout.setVisibility(View.GONE);
//			break;
//		}

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position1,
                            long id) {
        System.out.println(position1);
        deleteTag = position1;
        Email emaildata = adapter.getItem(position1);
        // Email emaildata = listems.get(position1);// 得到当前位置的邮件

        emaildata.setIsRead(true); // 邮件列表中position位置的邮件编辑为已读
        listems.remove(position1);// 数组中移除当前邮件
        listems.add(position1, emaildata);// 将设为已读的邮件插入当前位置

        adapter.notifyDataSetChanged();// gengxin listview

        // 传递数据跳转到邮件详情界面
        Intent intent = new Intent(EmailOutBoxAct.this, EmailDetailsAct.class);
        intent.putExtra("emailmap", emaildata);
        intent.putExtra("boxtype", boxType);
        intent.putExtra("emailtype", emailType);
        startActivityForResult(intent, 2);

    }

    /**
     * 邮件 listview适配器
     *
     * @author yqs
     */
    class ListAdapter extends BaseAdapter {
        List<Email> listems = new ArrayList<Email>();

        public ListAdapter(List<Email> listems) {
            this.listems = listems;
        }

        /**
         * 当ListView数据发生变化时,调用此方法来更新ListView
         *
         * @param list
         */
        public void updateListView(ArrayList<Email> list) {
            if (list == null) {
                this.listems = new ArrayList<Email>();
            } else {
                this.listems = list;
            }
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return listems.size();
        }

        @Override
        public Email getItem(int position) {
            return listems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(EmailOutBoxAct.this,
                        R.layout.inbox_listitems, null);
                new ViewHolder(convertView);
            }
            ViewHolder holder = (ViewHolder) convertView.getTag();
            Email item = getItem(position);
            // holder.outboxImage.setImageDrawable(getResources().getDrawable(
            // item.getImage()));
            holder.outboxImage.setImageDrawable(getResources().getDrawable(
                    R.drawable.outbox_image));

            holder.outboxAreceiver.setText(item.getTo());
            holder.emailTheme.setText(item.getSubject());
            holder.emailtime.setText(item.getSentdata());
            holder.emailContent.setText(item.getContent());
            if (item.getIsRead()) {
                holder.isReadImageView.setVisibility(View.INVISIBLE);
            } else {
                holder.isReadImageView.setVisibility(View.VISIBLE);

            }
            return convertView;
        }

        class ViewHolder {
            public ImageView outboxImage; // 发件箱用户头像
            public TextView outboxAreceiver;// 收件人姓名
            public TextView emailTheme;// 邮件主题
            public TextView emailtime;// 发送时间
            public TextView emailContent;// 邮件内容
            private ImageView isReadImageView;// 是否已读

            public ViewHolder(View view) {
                outboxImage = (ImageView) view.findViewById(R.id.inboximage);
                outboxAreceiver = (TextView) view
                        .findViewById(R.id.inbox_addresser);
                emailTheme = (TextView) view
                        .findViewById(R.id.inbox_emailtheme);
                emailtime = (TextView) view.findViewById(R.id.inbox_emailtime);
                emailContent = (TextView) view
                        .findViewById(R.id.inbox_emailcontent);
                isReadImageView = (ImageView) view.findViewById(R.id.isread);
                view.setTag(this);
            }
        }
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    /**
     * 左滑显示删除和标记未读
     */
    private void leftSlide() {
        creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                // 删除按钮
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        EmailOutBoxAct.this);
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(90));
                // set a icon
                deleteItem.setTitle(ResStringUtil.getString(R.string.common_text_delete));
                deleteItem.setTitleSize(18);
                // set item title font color
                deleteItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

        // set creator
        listView.setMenuCreator(creator);

        // step 2. listener item click event
        listView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu,
                                           int index) {
                menu.removeMenuItem(readItem);

                switch (index) {

                    // 点击删除
                    case 0:
                        System.out.println("listems.size:" + listems.size());
                        System.out.println(position);

                        showAlertDialog(position);
                        // Email deleteEmail = listems.get(position);
                        // deleteHeadEmail(deleteEmail.getMessageID());
                        // listems.remove(position);
                        // adapter.notifyDataSetChanged();
                        break;
                }
                return true;
            }

        });

    }

    private void showAlertDialog(final int position) {
        final Email deleteEmail = listems.get(position);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(ResStringUtil.getString(R.string.common_text_hint)).setMessage(ResStringUtil.getString(R.string.mobile_lib_email_delete))
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        deleteHeadEmail(deleteEmail.getMessageID());
                        listems.remove(position);
                        adapter.notifyDataSetChanged();
                        dialog.dismiss();

                    }
                }).setNegativeButton(R.string.common_text_cancel, null).show();

    }

    /**
     * 搜索框监听器
     */
    private void initListener() {

        /** 清除输入字符 **/
        ivClearText.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                etSearch.setText("");
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable e) {

                String content = etSearch.getText().toString();
//				Log.i(TAG, "content:" + content);
                if ("".equals(content)) {
                    ivClearText.setVisibility(View.INVISIBLE);
                } else {
                    ivClearText.setVisibility(View.VISIBLE);
                }
                if (content.length() > 0) {

                    ArrayList<Email> fileterList = (ArrayList<Email>) search(content);
                    adapter.updateListView(fileterList);

                } else {

                    adapter.updateListView(listems);
                }
                listView.setSelection(0);

            }

        });

    }

    /**
     * 模糊查询
     *
     * @param str 搜索输入的字符
     * @return
     */
    private ArrayList<Email> search(String str) {
        ArrayList<Email> filterList = new ArrayList<Email>();// 过滤后的list

        for (Email email : listems) {
            if (email.getTo() != null && email.getSubject() != null) {
                if (email.getSubject().contains(str)
                        || email.getTo().contains(str)
                        || email.getSentdata().contains(str)) {
                    filterList.add(email);

                }
            }

        }

        return filterList;
    }

    /**
     * 根据得到的返回值删除邮件
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == 2) {
            Boolean bool = false;
            bool = (Boolean) data.getSerializableExtra("deleteTag");
            if (bool) {
                deleteHeadEmail(listems.get(deleteTag).getMessageID());
                listems.remove(deleteTag);// deleteTag 是点击跳转的position
                adapter.notifyDataSetChanged();
            }

        }
    }

    /**
     * 加载发件箱数据
     */
    private void loadOutBoxData(final int pages) {
//		Log.i(TAG, "发件箱数据加载中...");
        new AsyncTask<Void, Void, JResponseObject>() {

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();
                // 加载dialog显示
                LoadingDataUtilBlack.show(EmailOutBoxAct.this);
            }

            @Override
            protected JResponseObject doInBackground(Void... params) {
                // 创建PO

                JParamObject PO = JParamObject.Create();
                JResponseObject RO = null;

                // tokenid
                tokenId = GlobalMap.getProperty(
                        emailType + "TokenId", "");
                if ("".equals(tokenId)) {
//					Log.i(TAG, "token不存在");
                    tokenId = GetTokenDataByPO.getEmailTokenid(emailType);
//					Log.i(TAG, "重新请求的token： " + tokenId);
                }

                PO.SetValueByParamName("WB_SYS_KEY", emailType);
                PO.SetValueByParamName(emailType + "_systemmethod",
                        "EmailOutBox");
                PO.SetValueByParamName(emailType + "_params_PageIndex",
                        String.valueOf(pages));
                PO.SetValueByParamName(emailType + "_params_tokenIDFromMoblie",
                        tokenId);

                try {
                    // 连接服务器
                    RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
                    System.out.println("..........");
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return RO;
            }

            @SuppressWarnings({"unused", "unchecked"})
            @Override
            protected void onPostExecute(JResponseObject result) {
                super.onPostExecute(result);

                String usereId = AndroidEnvironmentVariable.getUserID();
                String userName = AndroidEnvironmentVariable.getUserID();
                String password = AndroidEnvironmentVariable.getPassword();
                if (pages == 1) {
                    listems.removeAll(listems);// 清空list中的数据
                }
                if (result != null) {

                    map = result.getResponseMap();
                    if (map.containsKey(emailType)) {

                        emailEFDataSet = map.get(emailType);
                        if (emailEFDataSet != null) {

                            List<EFRowSet> list = emailEFDataSet
                                    .getRowSetArray();
                            EFDataSet oneDataSet = null;
                            // EFRowSet oneInfoRowSet = null;//一封邮件的
                            // 其中一条信息，比如邮件id
                            Map<String, Object> emailMap = new HashMap<String, Object>();
                            if (list != null) {
                                if (pages == 1) {
                                    listems.removeAll(listems);// 清空list中的数据
                                }
                                for (EFRowSet oneRowSet : list) {
                                    Email email = new Email();

                                    String emailId = (String) oneRowSet
                                            .getString("ID", "");
                                    String title = (String) oneRowSet
                                            .getString("Subject", "");
                                    String receivers = (String) oneRowSet
                                            .getString("Receivers", "");
                                    // 对于普光邮箱 收件人可能包含字符 <b> 去掉这些字符
                                    if (receivers.contains("<b>")) {
                                        receivers = receivers
                                                .replace("<b>", "");
                                        if (receivers.contains("</b>")) {
                                            receivers = receivers.replace(
                                                    "</b>", "");
                                        }
                                    }
                                    String sendTime = (String) oneRowSet
                                            .getString("DeleiverDate", "");

                                    Boolean isHaveAttach = (oneRowSet
                                            .getString("IsAttachment", ""))
                                            .equals("true") ? true : false;
                                    String toAddress = usereId + "@sinopec.com";

                                    email.setMessageID(emailId);
                                    email.setSubject(title);
                                    email.setTo(receivers);
                                    email.setImage(R.drawable.outbox_image);
                                    email.setIsHaveFile(isHaveAttach);
                                    email.setSentdata(sendTime);
                                    email.setIsRead(true);
                                    email.setUserId(userId);
                                    email.setEmailType(emailType);

                                    listems.add(email);

                                }
                            }
                        } else {
                            Toast.makeText(EmailOutBoxAct.this, ResStringUtil.getString(R.string.common_text_no_more_data),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(EmailOutBoxAct.this, ResStringUtil.getString(R.string.common_text_no_data),
                                Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(EmailOutBoxAct.this, ResStringUtil.getString(R.string.common_text_no_data),
                            Toast.LENGTH_SHORT).show();
                }

                adapter.notifyDataSetChanged();
                mSrl.finishRefresh();
                mSrl.finishLoadMore();
                LoadingDataUtilBlack.dismiss();
                if (pages == 1) {
                    outboxEmailsDAO.saveSetEmail(listems);
                }
            }

            protected void onCancelled() {
                mSrl.finishRefresh();
                mSrl.finishLoadMore();
            }

        }.executeOnExecutor(Executors.newCachedThreadPool());

    }

    /**
     * 根据id删除邮件
     *
     * @param messageID
     */
    private void deleteHeadEmail(final String messageID) {
//		Log.i(TAG, "删除邮件");
        new AsyncTask<Void, Void, JResponseObject>() {

            @Override
            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();

            }

            @Override
            protected JResponseObject doInBackground(Void... params) {
                // 创建PO

                JParamObject PO = JParamObject.Create();
                JResponseObject RO = null;

                // tokenid
                tokenId = GlobalMap.getProperty(
                        emailType + "TokenId", "");
                if ("".equals(tokenId)) {
//					Log.i(TAG, "token不存在");
                    tokenId = GetTokenDataByPO.getEmailTokenid(emailType);
//					Log.i(TAG, "重新请求的token： " + tokenId);
                }

                PO.SetValueByParamName("WB_SYS_KEY", emailType);
                PO.SetValueByParamName(emailType + "_systemmethod",
                        "EmailDelete");
                PO.SetValueByParamName(emailType + "_params_ItemID", messageID);
                PO.SetValueByParamName(emailType + "_params_tokenIDFromMoblie",
                        tokenId);
                PO.SetValueByParamName(emailType + "_params_boxflag", "outbox");

                try {
                    // 连接服务器
                    RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
                    System.out.println("..........");
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return RO;
            }

            @Override
            protected void onPostExecute(JResponseObject result) {
                super.onPostExecute(result);

                if (result != null) {
                    outboxEmailsDAO.deleteEmailById(messageID);
                    Toast.makeText(EmailOutBoxAct.this, ResStringUtil.getString(R.string.mobile_lib_email_delete_success),
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(EmailOutBoxAct.this, ResStringUtil.getString(R.string.mobile_lib_email_delete_fails),
                            Toast.LENGTH_SHORT).show();
                }

                adapter.notifyDataSetChanged();
                LoadingDataUtilBlack.dismiss();

            }

        }.executeOnExecutor(Executors.newCachedThreadPool());

    }

}
